$.ajaxSetup({contentType: "application/json; charset=utf-8"});
$.ajaxSettings.async = false;
/*
修改、新增公共类
url：请求接口,data：请求参数,index：关闭的弹窗下标
*/
function layuiPost(url,data,index){
	layer.load(2);
	var frontUserInfo = $.parseJSON(sessionStorage.getItem("userInfo"));
	if(frontUserInfo != null){
		return doPost(url,data,index)
	}
	$.post(getHttp()+'/webservice/getJurisdiction?token='+sessionStorage.getItem("token"), JSON.stringify({token:sessionStorage.getItem("token"),url:getUri(url)}), function (res) {
		layer.closeAll('loading');
		if(res.success){
			return doPost(url,data,index)
		}else{
			layer.msg(res.msg != null ? res.msg : res[0].msg,{icon:0,time:3000});
		}
	}, 'json');
}

function doPost(url,data,index){
	var flag = false,frontUserInfo = $.parseJSON(sessionStorage.getItem("userInfo"));
	if(url.indexOf("token") == -1) url = url + "?token="+sessionStorage.getItem("token")
	var header = {
		"token":sessionStorage.getItem("token"),
		'Content-Type': 'application/json'
	};
	if(frontUserInfo != null) header.userName = frontUserInfo.opendId;
	$.ajax({
		url: url,type: 'POST',dataType: 'json',
		data: JSON.stringify(data),cache: false,
		headers:header,
		success: function(res){
			layer.closeAll('loading');
			if(res.success){
				if(index != "notis"){
					layer.msg(res.msg,{icon:1,time:1500},function(){
						if(index == null) layui.table.reload('table', {});
						else if(index == "nofresh") index="不刷新"
						else if(index == "back") window.history.back();
						else parent.location.reload(); // 父页面刷新
					});
				}
				flag = res;
			}else{
				layer.msg(res.msg,{icon:0,time:3000},function(){
					if(res.code == "EL-0001") window.top.location="/login";
				});
				flag = res;
			}
		}
	})
	return flag;
}

/*
下载公共类
url：请求接口,data：请求参数,column：下载列名,name：表格名称
*/
function layuiDownload(url,data,column,name){
	layer.load(2);
	$.post(getHttp()+'/webservice/getJurisdiction?token='+sessionStorage.getItem("token"), JSON.stringify({token:sessionStorage.getItem("token"),url:getUri(url)}), function (res) {
		if(res.code == 0){
			$.post(url, JSON.stringify(data), function (res) {
				layer.closeAll('loading');
			    if (res.code==0) {
			    	layer.close(loading);
		            layer.msg(res.msg);
		            res.data.unshift(column);
		            layui.excel.exportExcel({
		                sheet1: res.data
		            }, name+'.xlsx', 'xlsx');
				}
			}, 'json');
		}else{
			layer.closeAll('loading');
			layer.msg(res.msg != null ? res.msg : res[0].msg,{icon:0,time:3000});
		}
	}, 'json');
}
if(getQueryString("token") != null && getQueryString("token") != ""){
	sessionStorage.setItem("token",getQueryString("token"))
}
//设置公共请求头
function getHttp(){
	var serverName = window.location.host;
	if(serverName.indexOf("localhost") > -1) return 'http://localhost';
	else return 'http://www.ywx168.cn';//测试
}
function geturl(){
	return '/front';
}
//最小日期（当前日期）
function minDate(){
    var now = new Date();
    return now.getFullYear()+"-" + (now.getMonth()+1) + "-" + now.getDate();
}
//以某个字符串结尾
String.prototype.endWith=function(str){
	var reg=new RegExp(str+"$");
	return reg.test(this);
}

function getUri(url) {
    var r = url.split("?");
    if (r != null) return r[0]; return null;
}

function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
}

/**
 去掉小数多余的0
 */
const cutZero = function (number) {
	if(Number.isInteger(number)) {
		return number
	}
	const [integer, decimal] = number.split('.')
	const formatDecimal = decimal.replace(/0*$/,'')
	return integer + (formatDecimal.length ? `.${formatDecimal}` : '')
}

//计算两个日期的相差天数
function daysBetween(sDate1,sDate2){
    //Date.parse() 解析一个日期时间字符串，并返回1970/1/1 午夜距离该日期时间的毫秒数
    var time1 = Date.parse(new Date(sDate1));
    var time2 = Date.parse(new Date(sDate2));
    var nDays = Math.abs(parseInt((time1 - time2)/1000/3600/24));
    return  nDays;
};
//获取当前日期追加天数之后的日期
function getDate(i) {   
	var oldTime = new Date().getFullYear()+'-'+(new Date().getMonth()+1)+'-'+new Date().getDate();//获取计算时间
	var day1 = new Date(oldTime);//String转date就是这么简单
	var daycount = (24*60*60*1000) * Number(i);
	day1.setTime(day1.getTime()+daycount);
	var month = (day1.getMonth()+1) > 10 ? (day1.getMonth()+1) : "0"+(day1.getMonth()+1);
	var day = (day1.getDate()+1) > 10 ? (day1.getDate()) : "0"+(day1.getDate());
	var s1 = day1.getFullYear()+"-" + month + "-" + day;
	return s1;
}
// 比较两个日期相差的毫秒数
function specifiedDate(startDate,endDate){
	if(isEmpty(startDate)) startDate = new Date();
	else startDate = new Date(startDate)
	if(isEmpty(endDate)) endDate = new Date();
	else endDate = new Date(endDate)
	return startDate.getTime() - endDate.getTime()
}
//增加水印
function showpicwater(pic,w,h){
	var urls = pic.split(",");
	var htmlIm = "";
	for (const imageUrl of urls) {
		//准备img对象
		var img = new Image();
		img.src = getPic(imageUrl);//这里是需要添加水印的背景图路径
		img.setAttribute("crossOrigin",'Anonymous')
		img.width= w;
		img.height=h;
		const canvas = document.createElement("canvas");
		let wmConfig = {
			font: 'microsoft yahei',
			textArray: ["云启科技"],
			density: 2.5
		}
		let fontSize = 16;
		let imgWidth = canvas.width;
		let imgHeight = canvas.height;
		var ctx=canvas.getContext("2d");
		var dataURL = null;
		// 加载完成开始绘制
		img.onload=function(){
			//准备canvas环境
			canvas.width = $(window).width()*w/100;
			canvas.height = $(window).height()*h/100;
			// 绘制图片
			ctx.drawImage(img,0,0,canvas.width,canvas.height);
			// 绘制水印
			ctx.font = `${fontSize}px ${wmConfig.font}`;
			ctx.lineWidth = 1;
			ctx.fillStyle = "#ffffff38";
			ctx.textAlign = "left";
			ctx.textBaseline = "middle";
			// //文字坐标
			const maxPx = Math.max(imgWidth, imgHeight);
			const stepPx = Math.floor(maxPx / wmConfig.density);
			let arrayX = [0];//初始水印位置 canvas坐标 0 0 点
			while (arrayX[arrayX.length - 1] < maxPx / 1) {
				arrayX.push(arrayX[arrayX.length - 1] + stepPx);
			}
			arrayX.push(...arrayX.slice(1, arrayX.length).map((el) => {
				return -el;
			}));
			for (let i = 0; i < arrayX.length; i++) {
				for (let j = 0; j < arrayX.length; j++) {
					ctx.save();
					ctx.translate(imgWidth / 2, imgHeight / 2); ///画布旋转原点 移到 图片中心
					ctx.rotate(-Math.PI / 5);
					if (wmConfig.textArray.length > 3) { //最多显示三行水印，也可以根据需要自定义
						wmConfig.textArray = wmConfig.textArray.slice(0, 3);
					}
					wmConfig.textArray.forEach((el, index) => {
						let offsetY = fontSize * index + 10;
						ctx.fillText(el, arrayX[i], arrayX[j] + offsetY);
					});
					ctx.restore();
				}
			}
			dataURL = canvas.toDataURL("image/png");
			htmlIm += "<img style='width:100%;height:100%;' src='" + dataURL + "' />"; //展示添加水印后的图片
			var carousel1 = "<div id='rotationChart' class='layui-carousel'><div carousel-item style='height:100%;'>" + htmlIm + "</div></div>"
			layer.open({
				type: 1,
				title: false,
				//maxmin: false,
				shade: 1,
				shadeClose: true,
				offset:'auto',
				closeBtn: 2,
				//skin: 'layui-layer-rim',
				area: [!isEmpty(w) ? w+"%" : '90%',!isEmpty(h) ? h+"%" : '90%'],
				anim: 0,
				isOutAnim: true,
				// fixed: false,
				resize: true,
				scrollbar: false,
				content: carousel1,
				success:function(){
					//先拼接 后加载layui 轮播
					layui.use('carousel', function(){
						var carousel = layui.carousel;
						//建造实例
						carousel.render({
							elem: '#rotationChart',
							width: '100%', //设置容器宽度
							height: '100%', //设置容器高度
							arrow: 'always', //始终显示箭头
							interval: 2000,
							// autoplay:true,
							full:false
							//,anim: 'updown' //切换动画方式
						});
					});
				},
			});
		}
	}
}

//无水印
function showpic(pic,w,h){
	var urls = pic.split(",");
	var htmlIm = "";
	for (const imageUrl of urls) {
		htmlIm += "<img style='width:100%;height:100%;' src='" + getPic(imageUrl) + "' />";
	}
	var carousel1 = "<div id='rotationChart' class='layui-carousel'><div carousel-item style='height:100%;'>" + htmlIm + "</div></div>"
	layer.open({
		type: 1,
		title: false,
		//maxmin: false,
		shade: 1,
		shadeClose: true,
		offset:'auto',
		closeBtn: 2,
		//skin: 'layui-layer-rim',
		area: [!isEmpty(w) ? w+"%" : '90%',!isEmpty(h) ? h+"%" : '90%'],
		anim: 0,
		isOutAnim: true,
		// fixed: false,
		resize: true,
		scrollbar: false,
		content: carousel1,
		success:function(){
			//先拼接 后加载layui 轮播
			layui.use('carousel', function(){
				var carousel = layui.carousel;
				//建造实例
				carousel.render({
					elem: '#rotationChart',
					width: '100%', //设置容器宽度
					height: '100%', //设置容器高度
					arrow: 'always', //始终显示箭头
					interval: 2000,
					// autoplay:true,
					full:false
					//,anim: 'updown' //切换动画方式
				});
			});
		},
	});
}
function getPic(pic){
	if(pic.startsWith("http")) return pic;
	else return "/"+pic;
}
function isEmpty(str){
	if(str == "" || str == null || str == "null" || str == undefined || str == "undefined") return true;
	else return false;
}
function getLimit(){
	return 20;
}

function cleardata(id,img,type){
	$('input[name="'+id+'"]').val('')
	$("#a"+id).html('')
	$.post("/delFile", JSON.stringify({fileName:img,type:type}), 'json')
}

function closeSwitch(data,status,em){
	if(status == 0){
		data.othis[0].classList.add('layui-form-onswitch');
		em.children('em').text('是');
	}else{
		data.othis[0].classList.remove('layui-form-onswitch');
		em.children('em').text('否');
	}
}
function closeSwitch1(data,status,em){
	if(status == 1){
		data.othis[0].classList.add('layui-form-onswitch');
		em.children('em').text('是');
	}else{
		data.othis[0].classList.remove('layui-form-onswitch');
		em.children('em').text('否');
	}
}

/**
 * 缺位补充0
 * @param type 需要加0的方式  1在原数值前，2在原数值后
 * @param index 需要补充的位数
 * @param num 需要补充的数字
 */
function addZero(type,index, num){
	var number = num.toString();
	if(index == number.length) return num
	else {
		for(var i = number.length; i < index; i++){
			if(type == 1) number = "0"+number
			else number = number + "0"
		}
	}
	return number
}




















// 订单通知
function getOrderStatus(){
	$.post('/front/cateringOrder/select?token='+sessionStorage.getItem("token"), JSON.stringify({status:1,isSure:0,orderStatus:"ORDER_STATUS_20"}), function (res) {
		if(res.data.length > 0){
			if ('speechSynthesis' in window) {
				// 创建一个新的SpeechSynthesisUtterance对象
				var utterance = new SpeechSynthesisUtterance('您有'+res.data.length+'条新的订单通知，请前往确认');
				// 配置语音属性（可选）
				// utterance.lang = 'zh-CN'; // 设置语言为中文
				// utterance.rate = 1; // 设置语速
				// utterance.pitch = 1; // 设置音调
				// utterance.volume = 1; // 设置音量
				// 开始播报
				window.speechSynthesis.speak(utterance);
				// 监听播报完成事件
				utterance.onend = function() {
					// alert('播报完成！');
				};
			} else {
				layer.msg('您的浏览器不支持语音播报功能。',{icon:0,time:1000});
			}
			var index = layui.layer.open({
				type: 1, title: '订单通知', id: 'lay_msg1',
				content: '<div style="width: 495px; height: 275px; border: 10px solid #F8F8F8; border-top-width: 0; padding: 10px; line-height:20px;  background-color: #fefbfb; color: black; font-size:14px; font-family:Courier New;">您有'+res.data.length+'条新的订单，请前往<a style="color:blue;" href="#" onclick="window.location.replace(\'/busorder\')" onfocus="closeAllLog()">确认</a>！</div>',
				shade: false, area: ['100%', '350px'], offset: 'b', anim: 2, time: 0, resize: false,
				end: function () {//无论是确认还是取消，只要层被销毁了，end都会执行，不携带任何参数。layer.open关闭事件
				}
			});
		}
	}, 'json');
}
function closeAllLog(){
	setTimeout(function(){layer.closeAll();},0)
}

var frontUserInfo = $.parseJSON(sessionStorage.getItem("userInfo"));
if(frontUserInfo != null) {
	if (frontUserInfo.isAdminUser == 1) {
		setTimeout(getOrderStatus, 1000);
		setInterval(getOrderStatus, 30000);
	}
}